package com.hong.zoo;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;

/**
 * Zookeeper的watcher机制示例
 */
public class ZkWatcherDemo {
    public static void main(String[] args) {
        // 创建一个zk客户端
        ZkClient client = new ZkClient("localhost:2181");

        //获取指定路径的子节点个数
        System.out.println(client.countChildren("/"));

        //如果节点存在则删除该节点
        if (client.exists("/dubbo")) {
            client.delete("/dubbo");
        }

        //创建永久节点
        String nodeName = client.create("/dubbo", "{name:admin}", CreateMode.PERSISTENT);
        System.out.println(nodeName);

        //创建临时节点
        client.createEphemeralSequential("/dubbo/test", "a");
        client.createEphemeralSequential("/dubbo/test", "b");

        System.out.println(client.countChildren("/dubbo"));

        //读取节点数据
        System.out.println(client.readData("/dubbo").toString());

        client.setZkSerializer(new MyZkSerializer());

        //订阅dubbo数据的变化
        client.subscribeDataChanges("/dubbo", new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println("===收到节点数据变化: "+ data +"===");
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("===收到节点被删除了===");
            }
        });

        //订阅dubbo子节点的变化
        client.subscribeChildChanges("/dubbo",(parentPath, currentChilds) -> System.out.println("dubbo节点发生变化"));

        //更新dubbo节点的数据
        client.writeData("/dubbo", "dubbo");

        /**
         * 注意以下几点：
         * 　1.不能删除已经存在子节点的节点
         * 　2.不能在临时节点上创建节点
         */

        try {
            System.in.read();
            Thread.sleep(1000*60*2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }catch (Exception e){

        }
    }
}
